<template>
    <a-drawer
        :keyboard="false"
        :maskClosable="false"
        placement="right"
        title="工单详览"
        :open="visible"
        :width="route.path.includes('follow-up') ? '80%' : '60%'"
        :confirmLoading="loading"
        centered
        @ok="handleSubmit"
        @close="handleCancel"
        :footer="false"
    >
        <template #extra>
            <a-space>
                <!-- <a-button type="primary" ghost @click="handleConfirm" v-if="[1].includes(modelRef.orderState)" v-permission="[`yfwy:order:take`]">接单</a-button> -->
                <a-button
                    type="primary"
                    danger
                    @click="transferModalVisible = true"
                    v-if="[1].includes(modelRef.orderState) && modelRef.transferToEstate != 1"
                    v-permission="[`yfwy:order:transferDJD`]"
                >
                    接单
                </a-button>
                <a-button
                    type="primary"
                    danger
                    @click="transferModalVisible = true"
                    v-if="[2].includes(modelRef.orderState) && modelRef.transferToEstate != 1 && (modelRef.orderChargePersonId === userStore.userId || showButtonByRoles)"
                    v-permission="[`yfwy:order:transferCLZ`]"
                >
                    转单
                </a-button>
                <!-- <a-button @click="changeCateModalVisible = true" v-permission="[`yfwy:order:updateClassify`]">修改分类</a-button> -->
                <template v-if="[2].includes(modelRef.orderState) && modelRef.transferToEstate != 1">
                    <a-button
                        v-if="modelRef.dataResource == 3 && (modelRef.orderChargePersonId === userStore.userId || showButtonByRoles)"
                        type="primary"
                        @click="rejectDcModalVisible = true"
                        v-permission="[`yfwy:order:transferDC`]"
                    >
                        驳回地产
                    </a-button>
                    <a-button
                        v-if="modelRef.dataResource != 3 && (modelRef.orderChargePersonId === userStore.userId || showButtonByRoles)"
                        type="primary"
                        @click="transferDcModalVisible = true"
                        v-permission="[`yfwy:order:transferDC`]"
                    >
                        转地产
                    </a-button>
                    <a-button v-if="modelRef.orderChargePersonId === userStore.userId || showButtonByRoles" @click="followModalVisible = true" v-permission="[`yfwy:order:follow`]">
                        跟进
                    </a-button>
                    <a-button type="primary" ghost @click="handleUrge" v-permission="[`yfwy:order:urge`]">催单</a-button>
                    <a-button
                        v-if="modelRef.orderChargePersonId === userStore.userId || showButtonByRoles"
                        type="primary"
                        danger
                        ghost
                        @click="handleClose"
                        v-permission="[`yfwy:order:close`]"
                    >
                        关单
                    </a-button>
                    <a-button
                        v-if="modelRef.orderChargePersonId === userStore.userId || showButtonByRoles"
                        type="primary"
                        danger
                        ghost
                        @click="forceCloseModalVisible = true"
                        v-permission="[`yfwy:order:forceClose`]"
                    >
                        强制关单
                    </a-button>
                    <a-button
                        type="primary"
                        v-if="modelRef.orderType == 0 && (modelRef.orderChargePersonId === userStore.userId || showButtonByRoles)"
                        danger
                        @click="cancelModalVisible = true"
                        v-permission="[`yfwy:order:cancel`]"
                    >
                        作废
                    </a-button>
                </template>
                <a-button
                    v-if="[6, 7, 8].includes(modelRef.orderState) && modelRef.transferToEstate != 1"
                    v-permission="['yfwy:order:spot']"
                    type="primary"
                    danger
                    ghost
                    @click="handleCheck"
                >
                    {{ modelRef.spotCheck == 1 ? '抽检详情' : '抽检' }}
                </a-button>
                <a-button v-permission="['yfwy:order:notify']" type="primary" ghost @click="handleInform">知会</a-button>
            </a-space>
        </template>
        <div class="wrap flex-col">
            <div class="info-top flex">
                <a-descriptions title="" :column="3">
                    <a-descriptions-item label="工单类型">{{ typeMap[modelRef.orderType] || '' }}</a-descriptions-item>
                    <a-descriptions-item label="工单状态">{{ statusMap[modelRef.orderState] || '' }}</a-descriptions-item>
                    <a-descriptions-item v-if="modelRef.transferToEstate != 1" label="当前责任人">
                        {{ modelRef.orderChargePerson || '' }}-{{ modelRef.orderChargePersonPhone || '' }}
                    </a-descriptions-item>
                    <a-descriptions-item v-if="modelRef.transferToEstate == 1" label="当前责任人">地产</a-descriptions-item>
                </a-descriptions>
            </div>
            <a-divider style="margin: 10px 0"></a-divider>
            <div class="flex info-wrap flex-1">
                <div class="left">
                    <a-descriptions title="工单详情" :column="1" :labelStyle="{ color: '#aaa', fontSize: '12px', width: '100px', textAlign: 'right' }">
                        <a-descriptions-item label="工单编号">{{ modelRef.orderNum || '' }}</a-descriptions-item>
                        <a-descriptions-item label="所属项目">{{ modelRef.projectName || '' }}</a-descriptions-item>
                        <a-descriptions-item label="房产号">{{ modelRef.propertyRoom || '' }}</a-descriptions-item>
                        <a-descriptions-item label="工单来源">{{ propertyMap[modelRef.orderProperty] || '' }} - {{ orderSourceShow }}</a-descriptions-item>
                        <a-descriptions-item label="报事报修时间">{{ modelRef.orderTime || '' }}</a-descriptions-item>
                        <a-descriptions-item label="联系人">{{ modelRef.contactPerson || '' }}</a-descriptions-item>
                        <a-descriptions-item label="联系电话">{{ modelRef.contactPersonPhone || '' }}</a-descriptions-item>
                        <!-- <a-descriptions-item label="提报人">
                            <span v-if="modelRef.orderProperty == 0">业主/ {{ modelRef.propertyOwner || '' }}</span>
                            <span v-else>{{ modelRef.creatorName || '' }}</span>
                        </a-descriptions-item> -->
                        <a-descriptions-item label="工单分类">{{ subMap[modelRef.orderTypeSub] }}-{{ modelRef.orderClassifyName || '' }}</a-descriptions-item>
                        <a-descriptions-item label="接单时间">{{ modelRef.taskingTime || '' }}</a-descriptions-item>
                        <a-descriptions-item v-if="modelRef.transferToEstate != 1" label="当前责任人">{{ modelRef.orderChargePerson || '' }}</a-descriptions-item>
                        <a-descriptions-item v-if="modelRef.transferToEstate == 1" label="当前责任人">地产</a-descriptions-item>
                        <a-descriptions-item label="工单内容">{{ modelRef.content || '' }}</a-descriptions-item>
                        <a-descriptions-item label="问题照片">
                            <a-image-preview-group>
                                <a-space>
                                    <template v-for="(item, index) in modelRef.fileList" :key="index">
                                        <audio controls :src="item.viewAddress" v-if="item.viewAddress.includes('.mp3') || item.viewAddress.includes('.m4a')"></audio>
                                        <a-button v-else-if="item.viewAddress.includes('.mp4')" @click="previewVideo(item)">点击查看视频</a-button>
                                        <a-image v-else :width="80" :height="80" :src="item.viewAddress" />
                                    </template>
                                </a-space>
                            </a-image-preview-group>
                        </a-descriptions-item>
                    </a-descriptions>
                </div>
                <a-divider type="vertical" style="height: 600px" />
                <div class="right">
                    <a-descriptions title="工单历史" :column="1" :labelStyle="{ color: '#aaa', fontSize: '12px' }"></a-descriptions>
                    <a-timeline v-if="modelRef.history">
                        <a-timeline-item v-for="item in modelRef.history" :key="item.id">
                            <div>{{ item.title }}（{{ item.operateName }}）</div>
                            <div>{{ item.operateTime }}</div>
                            <div v-if="item.content.userList">知会->{{ item.content.userList.map(item => item.name).join('、') }}</div>
                            <div v-if="item.content.orderChargePerson && item.content.orderChargePersonOld">
                                工单由【{{ item.content.orderChargePersonOld }}】转单给【{{ item.content.orderChargePerson }}】
                            </div>
                            <div v-if="item.content.satisfation">评分：{{ item.content.satisfation }}</div>
                            <div v-if="item.type == 15 && item.content.orderChargePerson">评价不满意升级转单给【{{ item.content.orderChargePerson }}】</div>
                            <div v-if="item.type == 27 && item.content.orderChargePersonNew">
                                工单由【{{ item.content.orderChargePerson }}】移交给【{{ item.content.orderChargePersonNew }}】
                            </div>
                            <div v-if="item.content.followTime">跟进时间：{{ item.content.followTime }}</div>
                            <div v-if="item.content.followTime">跟进途径：{{ item.content.followType === 0 ? '电话' : item.content.followType == 1 ? '面谈' : '信息' }}</div>
                            <div v-if="item.content.checkResult || item.content.checkResult == 0">抽检结果：{{ item.content.checkResult == 1 ? '合格' : '不合格' }}</div>
                            <div v-if="item.content.checkContent">抽检说明：{{ item.content.checkContent }}</div>
                            <div v-if="item.content.reason">{{ item.content.reason }}</div>
                            <template v-if="item.title === '审核'">
                                <div>审核结果: {{ item.content.approvalResult }}</div>
                                <div>审核说明: {{ item.content.approveOpinion || '' }}</div>
                            </template>
                            <template v-if="item.title === '作废'">
                                <div v-if="item.content.reasonValue == 'cancel_repeat'">
                                    重复工单:
                                    <a-typography-text underline style="cursor: pointer" @click="handleRepeat(item.content.orderNumRepeat)">
                                        {{ item.content.orderNumRepeat }}
                                    </a-typography-text>
                                </div>
                                <div v-else>作废原因：{{ item.content.reasonLabel }}</div>
                            </template>

                            <div v-if="Object.keys(item.content).length > 0">
                                <p>{{ item.content.txt }}</p>
                                <a-image-preview-group v-if="item.content.fileList.length > 0">
                                    <a-space>
                                        <!-- <a-image v-for="(file, index) in item.content.fileList" :key="index" :width="80" :height="80" :src="file.viewAddress" /> -->
                                        <template v-for="(file, index) in item.content.fileList" :key="index">
                                            <audio :src="file.viewAddress" controls v-if="file.viewAddress.includes('.mp3') || file.viewAddress.includes('.m4a')"></audio>
                                            <a-button v-else-if="file.viewAddress.includes('.mp4')" @click="previewVideo(file)">点击查看视频</a-button>
                                            <a-image v-else :width="80" :height="80" :src="file.viewAddress" />
                                        </template>
                                    </a-space>
                                </a-image-preview-group>
                            </div>
                        </a-timeline-item>
                    </a-timeline>
                </div>
                <div class="follow-wrap flex" v-if="[3, 4].includes(modelRef.orderState) && activeIndex != 9">
                    <a-divider type="vertical" style="height: 600px" />
                    <div>
                        <a-descriptions title="申请记录" :column="1" :labelStyle="{ color: '#aaa', fontSize: '12px' }">
                            <template v-if="[3, 4].includes(modelRef.orderState) && !isEmpty(modelRef.instanceVO)">
                                <a-descriptions-item label="关单类型">{{ followTypeMap[modelRef.instanceVO.flowType] || '' }}</a-descriptions-item>
                                <a-descriptions-item label="重复工单号" v-if="modelRef.instanceVO.orderNumRepeat">
                                    <a-typography-text underline style="cursor: pointer" @click="handleRepeat(modelRef.instanceVO.orderNumRepeat)">
                                        {{ modelRef.instanceVO.orderNumRepeat }}
                                    </a-typography-text>
                                </a-descriptions-item>
                                <a-descriptions-item label="申请原因">{{ modelRef.instanceVO.reason || '' }}</a-descriptions-item>
                                <a-descriptions-item label="申请说明">{{ modelRef.instanceVO.content || '' }}</a-descriptions-item>
                                <!-- <a-descriptions-item label="相关附件">
                            <a-image-preview-group v-if="modelRef.instanceVO.recordList.length > 0">
                                <a-space>
                                    <a-image v-for="(item, index) in modelRef.instanceVO.recordList" :key="index" :width="80" :height="80" :src="item.viewAddress" />
                                </a-space>
                            </a-image-preview-group>
                        </a-descriptions-item> -->
                            </template>
                        </a-descriptions>
                        <a-timeline v-if="!isEmpty(modelRef.instanceVO) && !isEmpty(modelRef.instanceVO.recordList)">
                            <a-timeline-item v-for="item in modelRef.instanceVO.recordList" :key="item.id">
                                <a-descriptions :column="1">
                                    <a-descriptions-item label="审核人">{{ item.userName || '' }}{{ item.roleName }}</a-descriptions-item>
                                    <a-descriptions-item label="审核结果">{{ stateMap[item.state] }}</a-descriptions-item>
                                    <a-descriptions-item label="审核时间" v-if="item.approveTime">{{ item.approveTime || '' }}</a-descriptions-item>
                                    <a-descriptions-item label="审核说明" v-if="item.approveTime">{{ item.approveOpinion || '' }}</a-descriptions-item>
                                </a-descriptions>
                            </a-timeline-item>
                        </a-timeline>
                        <div class="flex justify-around" style="width: 200px; margin: 20px auto" v-if="[3].includes(modelRef.orderState) && showExamine">
                            <a-button type="primary" size="large" ghost @click="handleAgree" v-permission="[`yfwy:process-record:pass`]">通过</a-button>
                            <a-button type="primary" size="large" danger @click="rejectModalVisible = true" v-permission="[`yfwy:process-record:reject`]">驳回</a-button>
                        </div>
                    </div>
                </div>
                <div class="follow-wrap flex" v-if="route.path.includes('follow-up')">
                    <a-divider type="vertical" style="height: 600px" />
                    <div>
                        <a-descriptions :title="`工单回访`" :column="1" :labelStyle="{ color: '#aaa', fontSize: '12px' }" />
                        <a-form>
                            <a-form-item label="工单说明" v-bind="validateInfos.visitContent">
                                <a-textarea v-model:value="modelRef.visitContent" show-count :disabled="modelRef.visitState != 1" :maxlength="500"></a-textarea>
                            </a-form-item>
                            <a-form-item label="上传附件" v-bind="validateInfos.visitRecord">
                                <custom-upload v-model:fileList="modelRef.visitRecord" v-if="modelRef.visitState == 1" upload-text="上传文档、照片、视频、音频"></custom-upload>
                                <a-image-preview-group v-if="modelRef.visitState != 1">
                                    <a-space>
                                        <template v-for="(file, index) in modelRef.visitRecord" :key="index">
                                            <audio controls :src="file.viewAddress" v-if="file.viewAddress.includes('.mp3') || file.viewAddress.includes('.m4a')"></audio>
                                            <a-button v-else-if="file.viewAddress.includes('.mp4')" @click="previewVideo(file)">点击查看视频</a-button>
                                            <a-image v-else :width="80" :height="80" :src="file.viewAddress" />
                                        </template>
                                    </a-space>
                                </a-image-preview-group>
                            </a-form-item>
                            <div class="flex justify-center" v-if="modelRef.visitState == 1">
                                <a-button type="primary" @click="handleFollowUpSubmit">保存</a-button>
                            </div>
                        </a-form>
                    </div>
                </div>
                <div class="follow-wrap flex" v-if="route.path.includes('inspect') && !route.path.includes('inspection')">
                    <a-divider type="vertical" style="height: 600px" />
                    <div>
                        <a-descriptions :title="`工单抽检`" :column="1" :labelStyle="{ color: '#aaa', fontSize: '12px' }" />
                        <a-form>
                            <a-form-item label="是否合格" v-bind="validateInfos.checkResult">
                                <a-radio-group v-model:value="modelRef.checkResult" :disabled="modelRef.spotCheck == 1">
                                    <a-radio :value="1">合格</a-radio>
                                    <a-radio :value="0">不合格</a-radio>
                                </a-radio-group>
                            </a-form-item>
                            <a-form-item label="说明" v-bind="validateInfos.checkContent">
                                <a-textarea v-model:value="modelRef.checkContent" show-count :maxlength="500" :disabled="modelRef.spotCheck == 1"></a-textarea>
                            </a-form-item>
                            <a-form-item label="上传附件">
                                <a-image-preview-group v-if="modelRef.spotCheck == 1">
                                    <a-space>
                                        <template v-for="(item, index) in modelRef.checkRecord" :key="index">
                                            <audio controls :src="item.viewAddress" v-if="item.viewAddress.includes('.mp3') || item.viewAddress.includes('.m4a')"></audio>
                                            <a-image v-else :width="80" :height="80" :src="item.viewAddress" />
                                        </template>
                                    </a-space>
                                </a-image-preview-group>
                                <custom-upload v-else v-model:fileList="modelRef.checkRecord"></custom-upload>
                            </a-form-item>
                            <div class="flex justify-center" v-if="modelRef.spotCheck == 0">
                                <a-button type="primary" @click="handleCheckSubmit">保存</a-button>
                            </div>
                        </a-form>
                    </div>
                </div>
            </div>
        </div>

        <change-cate-modal :model="modelRef" :visible="changeCateModalVisible" @cancel="changeCateModalVisible = false" @success="queryHandler" />
        <transfer-modal :model="modelRef" :visible="transferModalVisible" @cancel="transferModalVisible = false" @success="queryHandler" />
        <transfer-dc-modal
            :model="modelRef"
            :visible="transferDcModalVisible"
            @cancel="transferDcModalVisible = false"
            @success="
                () => {
                    closeModalVisible = false;
                    queryHandler();
                }
            "
        />
        <reject-dc-modal :model="modelRef" :visible="rejectDcModalVisible" @cancel="rejectDcModalVisible = false" @success="queryHandler" />
        <follow-modal :model="modelRef" :visible="followModalVisible" @cancel="followModalVisible = false" @success="queryHandler" />
        <force-close-modal :model="modelRef" :visible="forceCloseModalVisible" @cancel="forceCloseModalVisible = false" @success="queryHandler" />
        <close-modal :model="modelRef" :visible="closeModalVisible" @cancel="closeModalVisible = false" @success="queryHandler" @transfer="handleTransfer" />
        <cancel-modal :model="modelRef" :visible="cancelModalVisible" @cancel="cancelModalVisible = false" @success="queryHandler" />
        <reject-modal :model="modelRef" :visible="rejectModalVisible" @cancel="rejectModalVisible = false" @success="queryHandler" />
        <check-modal :model="modelRef" :visible="checkModalVisible" @cancel="checkModalVisible = false" @success="queryHandler" />
        <inform-modal :model="modelRef" :visible="informModalVisible" @cancel="informModalVisible = false" @success="queryHandler" />
    </a-drawer>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { computed } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, nextTick } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { createOrderClassify, updateOrderClassify } from '@/api/order/cate';
    import { cloneDeep, isEmpty, isUndefined, isString, isArray } from 'lodash-es';
    import { options, statusMap, propertyMap, typeMap, subMap, followTypeMap } from './common';
    import { getOrder, takeOrder, getOrderRecord, urgeOrder, visitOrder, pass, checkWarranty, spotCheckOrder } from '@/api/order/mine-list';
    import { dictDataListByDictType } from '@/api/user/dict';
    import { Modal } from 'ant-design-vue';
    import { useRoute } from 'vue-router';
    import ChangeCateModal from './change-cate-modal.vue';
    import TransferModal from './transfer-modal.vue';
    import CancelModal from './cancel-modal.vue';
    import TransferDcModal from './transfer-dc-modal.vue';
    import ForceCloseModal from './force-close-modal.vue';
    import FollowModal from './follow-modal.vue';
    import CloseModal from './close-modal.vue';
    import RejectModal from './reject-modal.vue';
    import CheckModal from './check-modal.vue';
    import InformModal from './inform-modal.vue';
    import RejectDcModal from './reject-dc-modal.vue';
    import { useUserStore } from '@/store/user';

    const userStore = useUserStore();

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success', 'repeat'],
        setup(props, { emit }) {
            console.log(userStore);

            const route = useRoute();

            const loading = ref(false);
            const roleList = ref<any[]>([]);
            const sourceData = ref<any[]>([]);
            const createDictData = ref<any[]>([]);
            const stateMap = {
                0: '待审核',
                1: '通过',
                2: '驳回',
            };
            const showButtonRoles = ['super_admin', '事业部品控'];
            const modelRef = reactive<any>({
                status: 1,
            });
            const rulesRef = reactive({
                classifyName: [{ required: true, message: '请输入分类名称' }],
                orderProfessionalLine: [{ required: true, message: '请选择条线' }],
                orderType: [{ required: true, message: '请选择工单类型' }],
                orderProperty: [{ required: true, message: '请选择工单属性' }],
                content: [{ required: true, message: '请输入工单描述' }],
                projectCode: [{ required: true, message: '请输入项目名称' }],
                contactPerson: [{ required: true, message: '请输入联系人姓名' }],
                contactPersonPhone: [{ required: true, message: '请输入联系人电话' }],
                orderTypeSub: [{ required: true, message: '请选择' }],
                orderSource: [{ required: true, message: '请选择' }],
                // checkResult: [{ required: true, message: '请选择' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            const activeIndex = ref(0);

            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    activeIndex.value = props.model.activeIndex ? props.model.activeIndex : 0;
                    if (props.model.orderNum) {
                        // Object.assign(modelRef, {
                        //     orderNum: props.model.orderNum,
                        // });
                        console.log('props.model', props.model);

                        queryHandler(props.model.orderNum);
                    }
                }
            });

            const orderSourceShow = computed(() => {
                if (sourceData.value.length > 0 && modelRef.orderSource) {
                    return sourceData.value.find(item => item.value === modelRef.orderSource).label;
                } else {
                    return '';
                }
            });

            const showExamine = ref(false);

            const showButtonByRoles = computed(() => {
                console.log(userStore);

                return showButtonRoles.some(item => userStore.info.roles.includes(item));
            });

            const queryHandler = async orderNum => {
                const orderInfo = await getOrder(orderNum ? orderNum : props.model.orderNum);
                dictDataListByDictType({
                    dictType: 'order_ascription',
                }).then(res => {
                    sourceData.value = res.data;
                });
                showExamine.value = false;

                if (!isEmpty(orderInfo.data.instanceVO)) {
                    orderInfo.data.instanceVO.recordList.forEach(item => {
                        if (!showExamine.value && userStore.info.roles.includes(item.roleName) && isEmpty(item.approveTime)) {
                            showExamine.value = true;
                        }
                    });
                }

                //   .then(res => {
                Object.assign(modelRef, orderInfo.data, {
                    orderTypeSub: isEmpty(orderInfo.data.orderTypeSub) ? [] : orderInfo.data.orderTypeSub.split(','),
                });
                //     });
                getOrderRecord(modelRef.id).then(res => {
                    (res.data || []).map(item => {
                        if (item.type == 19 && userStore.info.user.nickname == item.operateName) {
                            modelRef.checkResult = item.content.checkResult;
                            modelRef.checkRecord = item.content.checkRecord || [];
                            modelRef.checkContent = item.content.checkContent;
                        }
                        if (item.type == 17) {
                            modelRef.visitRecord = item.content.visitRecord || [];
                            modelRef.visitContent = item.content.visitContent;
                        }
                    });
                    modelRef.history = (res.data || []).map(item => {
                        const {
                            confirmFiles,
                            afterProcessFiles,
                            followRecord,
                            forceCloseFiles,
                            content,
                            detailContent,
                            followContent,
                            orderClassifyNameOld,
                            orderClassifyName,
                            visitRecord,
                            visitContent,
                            checkRecord,
                            checkContent,
                            checkResult,
                        } = item.content as any;

                        return {
                            ...item,
                            content: isString(item.content)
                                ? {
                                      txt: item.content,
                                      fileList: [],
                                  }
                                : {
                                      ...item.content,
                                      fileList: [
                                          ...(isArray(afterProcessFiles) ? afterProcessFiles || [] : afterProcessFiles ? [{ viewAddress: afterProcessFiles }] : []),
                                          //   ...(afterProcessFiles || []),
                                          ...(confirmFiles || []),

                                          ...(followRecord || []),
                                          ...(forceCloseFiles || []),
                                          ...(visitRecord || []),
                                          ...(checkRecord || []),
                                      ].filter(Boolean),
                                      txt:
                                          item.type === 3
                                              ? `原分类：${orderClassifyNameOld}-->现分类：${orderClassifyName}`
                                              : [content, detailContent, followContent, visitContent].filter(Boolean).join(''),
                                  },
                        };
                    });
                });
            };

            const handleConfirm = () => {
                Modal.confirm({
                    title: '接单确认',
                    content: '是否确认接单',
                    cancelText: '取消',
                    okText: '确认',
                    onOk() {
                        console.log('OK');
                        takeOrder(modelRef.id).then(() => {
                            message.success('接单成功');
                            queryHandler();
                        });
                    },
                    onCancel() {
                        console.log('Cancel');
                    },
                    class: 'test',
                });
            };

            const handleUrge = () => {
                Modal.confirm({
                    title: '催单确认',
                    content: '是否发起催单确认',
                    cancelText: '取消',
                    okText: '确认',
                    onOk() {
                        urgeOrder({ orderId: modelRef.id, orderState: modelRef.orderState }).then(() => {
                            message.success('发起成功');
                            queryHandler();
                        });
                    },
                    onCancel() {
                        console.log('Cancel');
                    },
                    class: 'test',
                });
            };

            const handleAgree = () => {
                Modal.confirm({
                    title: '审核确认',
                    content: '是否确认通过',
                    cancelText: '取消',
                    okText: '确认',
                    onOk() {
                        const { recordId, instanceId } = modelRef.instanceVO;
                        pass({ orderId: modelRef.id, instanceId, recordId }).then(res => {
                            if (res.code == 200) {
                                message.success('操作成功');
                                queryHandler();
                            }
                        });
                    },
                    onCancel() {
                        console.log('Cancel');
                    },
                });
            };

            const changeCateModalVisible = ref<boolean>(false);
            const transferDcModalVisible = ref<boolean>(false);
            const rejectDcModalVisible = ref<boolean>(false);
            const followModalVisible = ref<boolean>(false);
            const transferModalVisible = ref<boolean>(false);
            const closeModalVisible = ref<boolean>(false);
            const forceCloseModalVisible = ref<boolean>(false);
            const cancelModalVisible = ref<boolean>(false);
            const rejectModalVisible = ref<boolean>(false);

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                modelRef.status = 1;
                emit('cancel');
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    loading.value = true;

                    (isUndefined(modelRef.id) ? createOrderClassify : updateOrderClassify)({
                        ...(modelRef as any),
                        orderTypeSub: modelRef.orderTypeSub.join(','),
                    })
                        .then(res => {
                            if (res.code == 200) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };

            const handleFollowUpSubmit = () => {
                const { id, visitRecord = [], visitContent } = modelRef;
                if (isEmpty(visitContent)) {
                    return message.warning('请填写工单说明');
                }
                visitOrder({
                    orderId: id,
                    visitContent,
                    visitRecord,
                }).then(() => {
                    message.success('操作成功');
                    queryHandler();
                    nextTick(() => {
                        modelRef.visitREcord = [];
                        modelRef.visitContent = '';
                    });
                });
            };

            const handleCheckSubmit = () => {
                const { id, checkRecord = [], checkContent, checkResult } = modelRef;
                if (checkResult == 0 && isEmpty(checkContent)) {
                    return message.warning('请填写工单说明');
                }
                spotCheckOrder({
                    orderId: id,
                    checkResult,
                    checkRecord,
                    checkContent,
                }).then(() => {
                    message.success('操作成功');
                    queryHandler();
                    nextTick(() => {
                        modelRef.checkRecord = [];
                        modelRef.checkContent = '';
                    });
                });
            };

            const previewVideo = ({ viewAddress }) => {
                window.open(viewAddress, '_blank');
            };

            const handleRepeat = data => {
                emit('repeat', data);
            };

            const handleClose = () => {
                closeModalVisible.value = true;
                // checkWarranty(modelRef.projectCode).then(res => {
                //     if (!res.data) {
                //         closeModalVisible.value = true;
                //     } else {
                //         message.warning('质保期内不能关单');
                //     }
                // });
            };

            const checkModalVisible = ref<boolean>(false);
            const handleCheck = () => {
                checkModalVisible.value = true;
            };

            const informModalVisible = ref<boolean>(false);
            const handleInform = () => {
                informModalVisible.value = true;
            };

            const handleTransfer = () => {
                transferDcModalVisible.value = true;
            };
            const handleRejectTransfer = () => {
                rejectDcModalVisible.value = true;
            };

            return {
                activeIndex,
                rejectDcModalVisible,
                handleRejectTransfer,
                orderSourceShow,
                handleTransfer,
                informModalVisible,
                handleInform,
                checkModalVisible,
                handleCheck,
                showExamine,
                userStore,
                handleClose,
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                options,
                statusMap,
                propertyMap,
                typeMap,
                subMap,
                followTypeMap,
                roleList,
                sourceData,
                createDictData,
                isEmpty,

                handleConfirm,
                handleUrge,
                changeCateModalVisible,
                transferModalVisible,
                transferDcModalVisible,
                followModalVisible,
                forceCloseModalVisible,
                closeModalVisible,
                cancelModalVisible,
                rejectModalVisible,
                queryHandler,

                isString,
                route,
                handleFollowUpSubmit,
                handleCheckSubmit,

                handleAgree,

                previewVideo,
                stateMap,
                showButtonByRoles,
                handleRepeat,
            };
        },
        components: {
            ChangeCateModal,
            TransferModal,
            CancelModal,
            TransferDcModal,
            ForceCloseModal,
            CloseModal,
            FollowModal,
            RejectModal,
            CheckModal,
            InformModal,
            RejectDcModal,
        },
    });
</script>

<style lang="less" scoped>
    .wrap {
        height: 100%;
        display: flex;
    }
    .info-top {
        .left {
            width: 60%;
        }
    }
    .info-wrap {
        & > div {
            flex-shirk: 0;
        }
        // height: 100%;
        .left {
            width: 35%;
            margin-right: 10px;
            padding-right: 10px;
            overflow-y: auto;
            // height: 100%;
        }
        .right {
            flex: 1;
            overflow-y: auto;
            // height: 100%;
        }

        .follow-wrap {
            width: 30%;
        }
    }
</style>
